package com.atguigu.gmall.auth.service.impl;

import com.atguigu.gmall.auth.config.JwtProperties;
import com.atguigu.gmall.auth.feign.GmallUmsClient;
import com.atguigu.gmall.auth.service.AuthService;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.common.exception.GmallException;
import com.atguigu.gmall.common.utils.CookieUtils;
import com.atguigu.gmall.common.utils.IpUtils;
import com.atguigu.gmall.common.utils.JwtUtils;
import com.atguigu.gmall.common.utils.RsaUtils;
import com.atguigu.gmall.ums.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    GmallUmsClient umsClient;
    @Autowired
    JwtProperties jwtProperties;
    /*
        构建token的 cookie配置  和秘钥的配置 抽取到配置文件中管理
        秘钥构建时需要判断 秘钥文件是否存在，不存在需要重新构建
     */
//    String privateKeyPath = "F:\\keys\\rsa.pri";
//    int expireMinutes = 24*60;
//    String cookieName = "GMALL-TOKEN";
//    int cookieMaxAge = 24*60*60;
    @Override
    public void login(String loginName, String password, HttpServletRequest request , HttpServletResponse response) {
        try {
            //1、根据账号密码 远程访问ums服务查询用户数据
            ResponseVo<UserEntity> responseVo = umsClient.queryUser(loginName, password);
            UserEntity userEntity = responseVo.getData();
            if(userEntity==null){
                throw new RuntimeException();
            }
            //2、如果查询成功 构建token设置到响应头中
            Map<String, Object> map = new HashMap<>();//保存有效载荷(用户id、用户名称)
            map.put("userId" , userEntity.getId());
            map.put("username" , userEntity.getUsername());
            //map中存入登录时客户端的ip地址: 防止token被盗用
            map.put("ip" , IpUtils.getIpAddressAtService(request));
            String token = JwtUtils.generateToken(map , jwtProperties.getPrivateKey(),
                    jwtProperties.getExpireTime());
            //3、将token设置到响应头的cookie中
            CookieUtils.setCookie(request,response,jwtProperties.getCookieTokenName(),token ,
                    jwtProperties.getExpireTime()*60);
            //为了方便前端页面回显登录状态，将用户的昵称设置到cookie中
            CookieUtils.setCookie(request,response,jwtProperties.getUnick() , userEntity.getNickname() ,
                    jwtProperties.getExpireTime()*60 );
            //token=xxxx,unick=cuicui

        } catch (Exception e) {
            e.printStackTrace();
            //3、如果查询失败 账号密码错误，跳转到登录页面重新登录
            //登录失败
            throw new GmallException("登录账号或密码错误");
        }


    }
}
